/*
 * @Description: 数据字典
 * @Author: DSY
 * @Date: 2022-03-19 22:53:48
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-31 13:17:02
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { DataDicModel } from '@/api/system/model/dataDicModel'
import {
  apiDataDicGetNextSeqNumByTypeCode,
  apiDataDicSave,
  apiDataDicUpdateById
} from '@/api/system/dataDic'
import { log } from '../../../utils/logUtils'

export default defineComponent({
  name: 'DataDicForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const myData = reactive({
      parentId: '',
      parentName: ''
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      typeCode: '', // 类别编码
      typeName: '', // 类别名称
      dataValue: '', // 字典值
      dataName: '', // 字典值名称
      type: '1', // 字典类型（0，分类；1，字典）
      zxbs: '0', // 注销标示 （0，未注销；1，注销）
      dataNameEn: '', // 字典英文名称
      seqNum: 0, // 顺序号
      smartCode: '', // 助记码
      cssName: '', // 字典样式
      tag1: '', // 扩展1
      tag2: '', // 扩展2
      tag3: '', // 扩展3
      parentId: '', // 父ID
      remark: '' // 描述
    }

    let dbForm = reactive<DataDicModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      typeCode: [
        {
          required: true,
          message: '请输入类别编码',
          trigger: 'blur'
        }
      ],
      typeName: [
        {
          required: true,
          message: '请输入类别名称',
          trigger: 'blur'
        }
      ],
      dataValue: [
        {
          required: true,
          message: '请输入字典值',
          trigger: 'blur'
        }
      ],
      dataName: [
        {
          required: true,
          message: '请输入字典值名称',
          trigger: 'blur'
        }
      ],
      dataNameEn: [
        {
          required: false,
          message: '请输入字典英文名称',
          trigger: 'blur'
        }
      ],
      seqNum: [
        {
          required: false,
          message: '请输入顺序号',
          trigger: 'blur'
        }
      ],
      smartCode: [
        {
          required: false,
          message: '请输入助记码',
          trigger: 'blur'
        }
      ],
      tag1: [
        {
          required: false,
          message: '请输入扩展1',
          trigger: 'blur'
        }
      ],
      tag2: [
        {
          required: false,
          message: '请输入扩展2',
          trigger: 'blur'
        }
      ],
      tag3: [
        {
          required: false,
          message: '请输入扩展3',
          trigger: 'blur'
        }
      ],
      remark: [
        {
          required: false,
          message: '请输入描述',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(
      actionParam: string,
      rowParam?: DataDicModel,
      parentParams?: any,
      selectTreeNode?: any
    ) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
      } else {
        if (selectTreeNode.type === '1') {
          assign(dbForm, {
            typeCode: selectTreeNode.typeCode,
            typeName: selectTreeNode.typeName
          })
        }

        handleSearchNextSeqNumByTypeCode()
      }

      assign(myData, parentParams)
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      assign(dbForm, myData)
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('字典管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiDataDicSave(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(!isContinue)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiDataDicUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(true)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      if (isClosed) {
        assign(dbForm, cloneDeep(defaultForm))
        emit('refreshTableData')
        visible.value = false
      } else {
        assign(dbForm, {
          dataValue: '', // 字典值
          dataName: '', // 字典值名称
          dataNameEn: '', // 字典英文名称
          smartCode: '', // 助记码
          tag1: '', // 扩展1
          tag2: '', // 扩展2
          tag3: '', // 扩展3
          remark: '' // 描述
        })
        handleSearchNextSeqNumByTypeCode()
      }
    }

    /**
     * 查询下一个顺序号
     */
    function handleSearchNextSeqNumByTypeCode() {
      loading.value = true
      apiDataDicGetNextSeqNumByTypeCode(dbForm.typeCode ? dbForm.typeCode : '', '2')
        .then((result) => {
          if (result?.success) {
            dbForm.seqNum = result.data
          }
        })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      dbFormRef,
      dbForm,
      rules,
      myData,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset
    }
  }
})
